package com.cn.springcloudwechat.serviceImpl.attachment;

import com.cn.springcloudwechat.mapper.mapper.attachment.YmAttachmentMapper;
import com.cn.springcloudwechat.mapper.mapper.attachment.YmAttachmentRelevanceMapper;
import com.cn.springcloudwechat.model.attachment.YmAttachment;
import com.cn.springcloudwechat.model.attachment.YmAttachmentRelevance;
import com.cn.springcloudwechat.service.attachment.YmAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: Administrator
 * @create: 2018/8/10 10:09
 */
@Service("ymAttachmentServiceImpl")
public class YmAttachmentServiceImpl implements YmAttachmentService {
    @Autowired
    YmAttachmentRelevanceMapper ymAttachmentRelevanceMapper;
    @Autowired
    YmAttachmentMapper ymAttachmentMapper;

    private final static String RELEVANCE_TPYE__COURSE="5";


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAttachmentAndRelevance(List<YmAttachment> ymAttachments, Long relevanceId,
                                            String relevanceTpyeId) {
        int num = 0;
        if(!RELEVANCE_TPYE__COURSE.equals(relevanceTpyeId)){
            ymAttachmentRelevanceMapper.updateAttachmentRelevanceByRelevanceState(relevanceId, relevanceTpyeId, ymAttachments.get(0).getRelevanceTpyeDetail());
        }
        for (YmAttachment ymAttachment : ymAttachments) {
            ymAttachmentMapper.insertSelective(ymAttachment);
            //将原来的置为无效
            if(RELEVANCE_TPYE__COURSE.equals(relevanceTpyeId)){
                ymAttachmentRelevanceMapper.updateAttachmentRelevanceByRelevanceState(relevanceId, relevanceTpyeId, ymAttachment.getRelevanceTpyeDetail());
            }
            //添加关联关系
            YmAttachmentRelevance ymAttachmentRelevance = new YmAttachmentRelevance();
            ymAttachmentRelevance.setAttachmentId(ymAttachment.getAttachmentId());
            ymAttachmentRelevance.setRelevanceId(relevanceId);
            ymAttachmentRelevance.setRelevanceTpyeId(relevanceTpyeId);
            if (ymAttachment.getRelevanceTpyeDetail() == null) {
                ymAttachmentRelevance.setRelevanceTpyeDetail(0);
            } else {
                ymAttachmentRelevance.setRelevanceTpyeDetail(ymAttachment.getRelevanceTpyeDetail());
            }
            ymAttachmentRelevance.setState((short) 1);
            ymAttachmentRelevanceMapper.insertSelective(ymAttachmentRelevance);
            num++;
        }
        return num;
    }
}
